package com.huluobo.apps.pages

import android.os.Environment
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.apps.AppsIntent
import com.huluobo.apps.AppsViewModel
import com.huluobo.apps.entity.AppsEntity
import com.huluobo.apps.entity.AppsEntityItem
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseLoadingDialog
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_base.StateType
import com.huluobo.lib_base.UIState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

/**
 *  Created by LC on 2025/8/11.
 */

@Composable
fun AppsPage(navHostController: NavHostController, vm: AppsViewModel = hiltViewModel()) {
    val list = remember {
        SnapshotStateList<AppsEntityItem>()
    }

    var isShowProgress by remember {
        mutableStateOf(false)
    }

    var isShowLaunch by remember {
        mutableStateOf(false)
    }

    var currentProgress by remember {
        mutableStateOf(0f)
    }

    var scope = rememberCoroutineScope()

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.state.collect {
                when (it) {
                    is UIState.OnFailed -> {
                        isShowProgress = false
                        ToastUtils.showLong("获取应用程序列表失败:${it.msg}")
                        Log.e("TagA", "获取应用程序列表失败:${it.msg}")
                    }

                    UIState.OnLoading -> {
                        isShowProgress = true
                    }

                    is UIState.OnSuccess<*> -> {
                        isShowProgress = false
                        if (it.type == StateType.DEFAULT) {
                            list.clear()
                            list.addAll(it.data as AppsEntity)
                        }

                        if (it.type == StateType.DOWNLOAD) {
                            ToastUtils.showLong(it.data.toString())
                        }

                    }
                }
            }
        }
        vm.sendIntent(AppsIntent.GetApps)
    })

    if (isShowProgress) {
        BaseLoadingDialog()
    }

    Column(Modifier.padding(10.dp)) {
        BaseTitle(title = "在线应用", navHostController = navHostController)
        Spacer(modifier = Modifier.height(10.dp))
        LazyVerticalGrid(
            columns = GridCells.Fixed(2),
            content = {
                items(list) {
                    AppsItem(appsEntityItem = it, vm) {
                        isShowLaunch = true
                        scope.launch {
                            for (i in 1..100) {
                                currentProgress = i.toFloat() / 100
                                delay(100)
                            }
                            isShowLaunch = false
                            ToastUtils.showLong("安装成功")
                        }
                    }
                }
            },
            verticalArrangement = Arrangement.spacedBy(20.dp),
            horizontalArrangement = Arrangement.spacedBy(20.dp)
        )
    }

    if (isShowLaunch) {
        AlertDialog(onDismissRequest = {}, confirmButton = {}, text = {
            Column(verticalArrangement = Arrangement.spacedBy((10.dp))) {
                LinearProgressIndicator(progress = currentProgress)
                Text(text = "${(currentProgress * 100).toInt()}/100")
            }
        }, title = {
            Text(text = "安装中...")
        })
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun AppsItem(appsEntityItem: AppsEntityItem, vm: AppsViewModel, longClick: () -> Unit) {
//    val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

    val file = BaseApp.context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)

    var isShow by remember {
        mutableStateOf(false)
    }

    Column(verticalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.combinedClickable(
        onClick = {
            isShow = true
        },
        onLongClick = {
            longClick()
        }
    )) {
        AsyncImage(
            model = appsEntityItem.appIcon,
            contentDescription = "",
            modifier = Modifier
                .fillMaxWidth()
                .size(80.dp),
            alignment = Alignment.Center
        )
        Text(text = "名称 : ${appsEntityItem.appName}", fontWeight = FontWeight.Bold)
        Text(text = "网址 : ${appsEntityItem.netUrl}", maxLines = 1, overflow = TextOverflow.Ellipsis)
        Text(text = "创建时间 : ${appsEntityItem.createTime}", color = Color.LightGray, fontSize = 13.sp)
        Text(text = "更新时间 : ${appsEntityItem.updateTime}", color = Color.LightGray, fontSize = 13.sp)
    }

    if (isShow) {
        AlertDialog(onDismissRequest = {
            isShow = false
        }, confirmButton = {
            TextButton(onClick = {
                vm.sendIntent(
                    AppsIntent.DownloadApk(
                        appsEntityItem.apkUrl,
                        File(file, appsEntityItem.appName + ".apk")
                    )
                )
                isShow = false
            }) {
                Text(text = "确认")
            }
        }, dismissButton = {
            TextButton(onClick = {
                isShow = false
            }) {
                Text(text = "取消")
            }
        }, title = {
            Text(text = "下载提醒")
        }, text = {
            Text(text = "是否要下载${appsEntityItem.appName}吗?")
        })
    }
}